package com.lee.auth.security.config;

import com.lee.auth.security.filter.ResponseOutput;
import com.lee.auth.security.filter.TokenFilter;
import com.lee.auth.security.token.TokenService;
import com.lee.auth.security.filter.AuthenticationFilter;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

/**
 * @author Lee HN
 * @date 2019/11/11 9:23
 */
@Configuration
public class AuthBeanConfig {

    /**
     * 添加token过滤器  解析token
     *
     * @param TokenService
     * @return
     */
    @Bean
    public FilterRegistrationBean<TokenFilter> tokenFilter(TokenService TokenService) {
        FilterRegistrationBean<TokenFilter> registrationBean =
                new FilterRegistrationBean<>(new TokenFilter(TokenService));
        registrationBean.setName("tokenFilter");
        registrationBean.setOrder(0);
        return registrationBean;
    }

    @Bean
    public FilterRegistrationBean<AuthenticationFilter> authenticationFilter(PathSecurityConfigurer configurer,
                                                                             ResponseOutput responseOutput) {
        PathSecurity pathSecurity = new PathSecurity();
        configurer.configure(pathSecurity);
        FilterRegistrationBean<AuthenticationFilter> registrationBean =
                new FilterRegistrationBean<>(new AuthenticationFilter(pathSecurity.handlers(), responseOutput));
        registrationBean.setName("authenticationFilter");
        registrationBean.setOrder(1);
        return registrationBean;
    }

    @Bean
    @ConditionalOnMissingBean(PathSecurityConfigurer.class)
    public PathSecurityConfigurer pathSecurityConfigurer() {
        return s -> {};
    }

    /**
     * 默认密码处理器
     *
     * @return
     */
    @Bean
    @ConditionalOnMissingBean(PasswordEncoder.class)
    public PasswordEncoder passwordEncoder() {
        // bcrypt的加密强度4-31 选择较低的5已经够用 同时效率也比较高
        return new BCryptPasswordEncoder(5);
    }

}
